<?php

namespace app\user\logic;

use app\common\exception\LogicException;
use app\model\Barn;
use app\model\Disinfect;
use app\model\Fence;
use app\model\Pig;
use app\model\PigWeight;

class BarnLogic
{
    /**
     * @Description 列表
     * @author: zj
     * @param array $param
     * @time 2023/08/26 16:55:24
     * @return mixed
     */
    public function getList(array $param)
    {
        $factoryId = request()->user_info['factory_id'];

        $barnModel = new Barn();
        $query = $barnModel -> alias('b')
            ->leftJoin("factory f","f.id = b.factory_id")
            ->field("b.out_id as id,b.factory_id,f.name as factory,b.name as building,f.contacts,f.address,b.record_time,b.create_time")
            ->where('b.factory_id',$factoryId)
            ->where('b.delete_time',$barnModel::IS_DELETE_NO);

        if ($param['name']) {
            $query->where("b.name","like","%".trim($param['name'])."%");
        }

        $list = $query->order("b.out_id ASC")
            ->paginate([
                'list_rows' => $param['page_size'],
                'page' => $param['page']
            ])
            ->toArray();

        $fenceModel = new Fence();
        $pigModel = new Pig();
        
        foreach ($list['data'] as &$value) {
            $fenceCount = $fenceModel->checkFenceCount($factoryId,$value['id']);
            $value['fence_count'] = $fenceCount;
            
            $pigCount = $pigModel->checkPigCount($factoryId,$value['id']);
            $value['pig_count'] = $pigCount;

            $hardwareAbnormalCount = $fenceModel->checkFenceCount($factoryId,$value['id'],$fenceModel::HARDWARE_ABNORMAL);
            $value['hardware_abnormal'] = $hardwareAbnormalCount;
        }
        unset($value);

        return $list;
    }

    /**
     * @Description 获取详情
     * @author: zj
     * @param int $id
     * @time 2023/08/30 10:17:43
     * @return mixed
     */
    public function getDetail(int $id)
    {
        $factoryId = request()->user_info['factory_id'];
        $barnModel = new Barn();
        $info = $barnModel -> alias('b')
            ->join("factory f","f.id = b.factory_id","left")
            ->where('b.id',$id)
            ->where('b.delete_time',$barnModel::IS_DELETE_NO)
            ->field('b.out_id as id,b.name,b.factory_id,f.name as factory,b.record_time,b.create_time')
            ->find();
        if (!$info) {
            throw new LogicException("猪栋不存在");
        }
        $info = $info->toArray();

        // 统计 猪栏数量
        $fenceModel = new Fence();
        // 栋 猪栏id集
        $fenceIds = $fenceModel->where("out_barn_id",$info['id'])->where('delete_time',$fenceModel::IS_DELETE_NO)->column('id');
        // 栋 全部猪栏数
        $allPenCount = $fenceModel->checkFenceCount($factoryId,$info['id']);
        // 栋 异常猪栏数
        $abnormalPenCount = $fenceModel->checkFenceCount($factoryId,$info['id'],0);
        // 栋 正常猪栏数
        $normalPenCount = $fenceModel->checkFenceCount($factoryId,$info['id'],1);

        // 统计猪的数量
        $pigModel = new Pig();
        // 栋 里 全部猪的数量
        $allPigCount = $pigModel->checkPigCount($factoryId,$info['id']);
        // 健康的猪数量
        $healthPigCount = $pigModel->checkPigCount($factoryId,$info['id'],0,$pigModel::STATUS_HEALTH);
        // 疑似健康的猪数量
        $ysjkPigCount = $pigModel->checkPigCount($factoryId,$info['id'],0,$pigModel::STATUS_POTENTIAL_HEALTH);
        // 生病的猪数量
        $sickenPigCount = $pigModel->checkPigCount($factoryId,$info['id'],0,$pigModel::STATUS_SICK);
        // 已处理，待观察猪数量
        $treatPigCount = $pigModel->checkPigCount($factoryId,$info['id'],0,$pigModel::STATUS_OBSERVATION);
        // 治疗无效
        $treatmentIneffectiveCount = $pigModel->checkPigCount($factoryId,$info['id'],0,$pigModel::STATUS_INEFFECTIVE);
        // 最近消毒时间
        $dfModel = new Disinfect();
        $lastDisinfect = $dfModel->getLastDisinfectTime($factoryId,$info['id']);
        $info['last_disinfect'] = $lastDisinfect ? date("Y-m-d H:i:s",$lastDisinfect['record_time']) : "";

        // 统计数据
        $statisticData = [
            'fence_ids' => $fenceIds,
            'pens' => $allPenCount,
            'abnormal_pens' => $abnormalPenCount,
            'normal_pens' => $normalPenCount,
            'all_husbandry' => $allPigCount,
            'health_num' => $healthPigCount,
            'suspectedhealthy_num' => $ysjkPigCount,
            'sick_num' => $sickenPigCount,
            'treat_num' => $treatPigCount,
            'treatment_ineffective' => $treatmentIneffectiveCount
        ];

        return array_merge($info,$statisticData);
    }

    /**
     * @Description 下拉列表
     * @author: zj
     * @param array $param
     * @time 2023/08/26 16:59:42
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getSelectList(array $param)
    {
        $factoryId = request()->user_info['factory_id'];
        $barnModel = new Barn();
        $query = $barnModel->field("out_id as id,name")
            ->where('factory_id',$factoryId)
            ->where("delete_time",$barnModel::IS_DELETE_NO);

        if ($param['name']) {
            $query->where('name','like','%'.trim($param['name']).'%');
        }

        return $query->order("out_id ASC")
            ->paginate([
                'list_rows' => $param['page_size'],
                'page' => $param['page']
            ])
            ->toArray();
    }

    /**
     * @Description 编辑修改
     * @author: zj
     * @param int $factoryId
     * @param array $param
     * @time 2023/09/20 10:12:38
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(int $factoryId,array $param)
    {
        $buildingModel = new Barn();
        $building = $buildingModel->field('id,name,out_id')
            ->where('factory_id',$factoryId)
            ->where('id',$param['id'])
            ->where('delete_time',$buildingModel::IS_DELETE_NO)
            ->find();
        if (!$building) {
            throw new LogicException('栋不存在');
        }
        $building = $building->toArray();
        $exist = $buildingModel->checkName($factoryId, $param['name']);
        if ($exist && $exist != $building['id']) {
            throw new LogicException('栋名已存在');
        }
        $buildingModel->where('id',$param['id'])
            ->update([
                'name' => $param['name'],
                'update_time' => request()->time()
            ]);

        return true;
    }

    /**
     * @Description 使用某一食谱的猪栋列表
     * @author: zj
     * @param array $param
     * @time 2024/03/27 09:28:05
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function useCookBookBarn(array $param)
    {
        $factoryId = request()->user_info['factory_id'];
        $model = new Barn();
        $query = $model->field('out_id as id,name as barn,feed_plan_id')
            ->where('factory_id',$factoryId)
            ->where('delete_time',$model::IS_DELETE_NO);
        if ($param['feed_plan_id']) {
            $query->where('feed_plan_id',$param['feed_plan_id']);
        }

        $list = $query->order('out_id DESC')
            ->paginate([
                'list_rows' => $param['page_size'],
                'page' => $param['page']
            ])
            ->toArray();

        $pigModel = new Pig();

        foreach ($list['data'] as &$value) {
            $total = $pigModel->checkPigCount($factoryId,$value['id']);
            $useCookbookCount = $pigModel->where('factory_id',$factoryId)
                ->where('out_barn_id',$value['id'])
                ->where('feed_plan_id',$param['feed_plan_id'])
                ->where('exit_time',$pigModel::IS_EXIT_NO)
                ->where('delete_time',$pigModel::IS_DELETE_NO)
                ->count();

            $value['total'] = $total;
            $value['use_count'] = $useCookbookCount;
            $value['fence'] = '';
        }
        unset($value);

        return $list;
    }
}